package com.roubsite.cloud.common.utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtils {
    private static final String ALGORITHM = "RSA";
    private static final String publicKeyString = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCOP9X7EYxhuZAs02FL5vxu0kPqOUAyF" +
                                                  "ibA1G6EtsiL0yHuPimXffXdcEah6mktnJ+bh59j9B4h3971/zWV9JT6yUkKNjf6g74bEu" +
                                                  "fqgQGDF5uObKWroeZm2NWVnqeOydEc9ijVFGdaScBaonEVSGjMgZCpJS3R7TaP3iJ9gWU" +
                                                  "aGwIDAQAB"; // 替换为您的公钥字符串
    private static final String privateKeyString = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAI4/1fsRjGG5kCzTYUvm" +
                                                   "/G7SQ+o5QDIWJsDUboS2yIvTIe4+KZd99d1wRqHqaS2cn5uHn2P0HiHf3vX/NZX0lPrJ" +
                                                   "SQo2N/qDvhsS5+qBAYMXm45spauh5mbY1ZWep47J0Rz2KNUUZ1pJwFqicRVIaMyBkKkl" +
                                                   "LdHtNo/eIn2BZRobAgMBAAECgYAB+bymNCavyWzJVUAx1n86p3HpBAAyZzYE5zkHtSV7" +
                                                   "h6RI05Uun5cKtb9NYAeI6iFvVAawfoNCnizRsXMpkNAsLCf1rRKHOhEAZSJ5l+vm4eYw" +
                                                   "0/UasxzVkx2CSc5eq0Nu+gYEoqujVQYb+7JjD7dlXPy+YxNxZuRlDKPE6crv0QJBALs6" +
                                                   "oPeP4MCTzjte7TfhRnLAu2HC70jaS1PgI2NkGHMQgYZK/L9sTy2j1QIyJCi7I36GJ69+" +
                                                   "J7IxYvmM/kPHjssCQQDCf7cZkM/bMju9dfCQYa/I+h8taCcfGMI7MkYf46ah6mbOI7H6" +
                                                   "zfI4ESzw0YzSq4c+674Hni+M+RjpyqRBvGfxAkEAn/dVtG6vfppKaBuQ3l+RS1Y0QzDE" +
                                                   "NSCdn4ovcioBYb5GjDDhhcPKWppR0lB46HwLtXx1x9EnpW3gvIqka9DCxQJAbK1GFt/m" +
                                                   "dHkGDl/3EgWzXh38C7gVm/eOl9sIecsPEYvS873YNeabQB7AuLKt+Azl3g+FN+Z4dVG+" +
                                                   "TOvwidaHUQJBAKPHAm+2L/oPKJ8fha6rCmVx+bGl1HTYvLo3ukBN/bsyD3tz7u3V+8XO" +
                                                   "PBhytXQBGJbyTtE/GsBgq8PuELnZugM="; // 替换为您的私钥字符串
    private static final PublicKey publicKey;
    private static final PrivateKey privateKey;

    static {
        try {
            //生成公私钥的两种方式
            //1、使用base64方式生成公私钥
            publicKey = getPublicKeyFromString(publicKeyString);
            privateKey = getPrivateKeyFromString(privateKeyString);
            //2、系统随机生成
//            KeyPair keyPair = generateKeyPair();
//            publicKey = keyPair.getPublic();
//            System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
//            privateKey = keyPair.getPrivate();
//            System.out.println(Base64.getEncoder().encodeToString(privateKey.getEncoded()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
	}


    private static PublicKey getPublicKeyFromString(String publicKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    private static PrivateKey getPrivateKeyFromString(String privateKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyString);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

    private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(1024); // 设置密钥长度为2048位
        return keyPairGenerator.generateKeyPair();
    }

    public static String encrypt(String data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedData) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) {
        try {
            // 生成密钥对
            KeyPair keyPair = generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            String data = "Hello, World!";

            // 使用公钥加密
            String encryptedData = encrypt(data);
            System.out.println("Encrypted data: " + encryptedData);
 encryptedData = encrypt(data);
            System.out.println("Encrypted data: " + encryptedData);

            // 使用私钥解密
            String decryptedData = decrypt(encryptedData);
            System.out.println("Decrypted data: " + decryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
